package com.lianboke.link.ad.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lianboke.link.ad.R;
import com.lianboke.link.ad.VolleyUtils.HttpCallBack;
import com.lianboke.link.ad.VolleyUtils.HttpUtil;
import com.lianboke.link.ad.ad.YOUMiADUitil;
import com.lianboke.link.ad.app.MyApplication;
import com.lianboke.link.ad.beans.UserAccountModel;
import com.lianboke.link.ad.common.CommonParams;
import com.lianboke.link.ad.dbmanager.OrderDetailsCacheUtils;
import com.lianboke.link.ad.entry.OrdetTypeTable;
import com.lianboke.link.ad.services.TimerOrderService;
import com.lianboke.link.ad.updateUtils.AppUtils;
import com.lianboke.link.ad.updateUtils.UpdateAppManager;
import com.lianboke.link.ad.utils.AlarmManagerUtils;
import com.lianboke.link.ad.utils.DateUtil;
import com.lianboke.link.ad.utils.DeviceUtils;
import com.lianboke.link.ad.utils.FileUtil;
import com.lianboke.link.ad.utils.KLog;
import com.lianboke.link.ad.utils.NetWorkUtils;
import com.lianboke.link.ad.utils.SharedPreferencesUtil;
import com.lianboke.link.ad.utils.SystemUtils;
import com.lianboke.link.ad.utils.ToastUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.waps.AppConnect;

/**
 *
 * 新版主页
 */
public class MainNewActivity extends BaseActivity {

    //任务信息
    @BindView(R.id.rl_order_1)
    public RelativeLayout rl_order_1;
    @BindView(R.id.rl_order_2)
    public RelativeLayout rl_order_2;
    @BindView(R.id.rl_order_3)
    public RelativeLayout rl_order_3;
    @BindView(R.id.rl_order_4)
    public RelativeLayout rl_order_4;

    //通知
    @BindView(R.id.tv_note_1)
    public TextView tv_note_1;

    @BindView(R.id.tv_note_2)
    public TextView tv_note_2;

    @BindView(R.id.tv_note_3)
    public TextView tv_note_3;

    @BindView(R.id.loading_progress)
    public ProgressBar loading_progress;

    //自定义handler
    private MyOrderHandler myOrderHandler;

    //个人信息
    @BindView(R.id.tv_account)
    public TextView tv_account;

    @BindView(R.id.tv_yiti)
    public TextView tv_yiti;

    @BindView(R.id.tv_weiti)
    public TextView tv_weiti;

    @BindView(R.id.tv_tizhong)
    public TextView tv_tizhong;

    @BindView(R.id.tv_dongjie)
    public TextView tv_dongjie;


    private UserAccountModel userAccountModel;

    //提现
    @BindView(R.id.ll_user_account)
    public LinearLayout ll_user_account;

    //定时
    @BindView(R.id.ll_user_time)
    public LinearLayout ll_user_time;


    @BindView(R.id.tv_order_cache_flag)
    public TextView tv_order_cache_flag;

    @BindView(R.id.tv_order_count)
    public TextView tv_order_count;

    @BindView(R.id.tv_order_renling)
    public TextView tv_order_renling;

    @BindView(R.id.tv_order_finish)
    public TextView tv_order_finish;

    @BindView(R.id.tv_orders_unfinish_flag)
    public TextView tv_orders_unfinish_flag;


    //积分任务兑换
    @BindView(R.id.tv_youmi_ad)
    public TextView tv_youmi_ad;//有米

    @BindView(R.id.tv_wanpu_ad)
    public TextView tv_wanpu_ad;//万普

    //数据库操作订单详情
    private OrderDetailsCacheUtils orderDetailsCacheUtils ;

    //定时
    private int iCurrenthourOfDay;//每天小时
    private int iCurrentminute;//分钟




    @Override
    public int getContentViewId() {
        return R.layout.activity_main_new;
    }

    @Override
    public void initActivityParams(Bundle savedInstanceState) {

        //有米初始化
        YOUMiADUitil.initYOUMIParams(actContext);
        orderDetailsCacheUtils = new OrderDetailsCacheUtils(actContext);
        myOrderHandler = new MyOrderHandler(this);
        rl_order_1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //单击跳转到装机任务页面
                Intent mIntent = new Intent(actContext,OrderTypeListActivity.class);
                mIntent.putExtra("data",1);
                startActivity(mIntent);
            }
        });
        rl_order_2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //单击跳转到装机任务页面
                Intent mIntent = new Intent(actContext,OrderTypeListActivity.class);
                mIntent.putExtra("data",2);
                startActivity(mIntent);
            }
        });
        rl_order_3.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //单击跳转到装机任务页面
                Intent mIntent = new Intent(actContext,YouMiAdActivity.class);
                mIntent.putExtra("data",3);
                startActivity(mIntent);
            }
        });
        rl_order_4.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //单击跳转到装机任务页面
                Intent mIntent = new Intent(actContext,WanPuAdActivity.class);
                mIntent.putExtra("data",4);
                startActivity(mIntent);
            }
        });

        ll_user_account.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //单击跳转用户账户
                Intent mIntent = new Intent(actContext,UserAccountActivity.class);
                startActivity(mIntent);
                overridePendingTransition(R.anim.in_from_right,R.anim.out_to_left);

            }
        });
        //缓存任务
        tv_order_cache_flag.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(actContext,OrderCacheActivit.class);
                startActivity(mIntent);
            }
        });

        //定时
        ll_user_time.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //单击跳转用户账户
                Intent mIntent = new Intent(actContext,UserOrderTimeActivity.class);
                startActivity(mIntent);
                overridePendingTransition(R.anim.in_from_left,R.anim.out_to_right);
            }
        });

        tv_note_1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(actContext,MediaActivity.class);
                startActivity(mIntent);
            }
        });
        tv_note_2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(actContext,MyWebViewActivity.class);
                mIntent.putExtra("type",4);
                startActivity(mIntent);
            }
        });
        //升级信息提示
        tv_note_3.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(actContext,MyWebViewActivity.class);
                mIntent.putExtra("type",3);
                startActivity(mIntent);
            }
        });

        tv_orders_unfinish_flag.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //未完成任务列表
                Intent mIntent = new Intent(actContext,OrdersUnFinishListActivity.class);
                startActivity(mIntent);
            }
        });

        //有米广告
        tv_youmi_ad.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(actContext,YouMiAdActivity.class);
                startActivity(mIntent);
            }
        });
        //有米广告
        tv_wanpu_ad.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(actContext,WanPuAdActivity.class);
                startActivity(mIntent);
            }
        });

        //清楚缓存过时缓存数据
        delOrderTypeCacheInfo();

        //初始化定时器
        initAlarmOrderTimer();

        if(SystemUtils.phoneRootCommand("chmod 777 "+getPackageCodePath())){
            //升级检查
            startAppUpdate();
        }else{
            ToastUtil.showShort(actContext,"拒绝root权限将无法自动安装任务");
        }

        KLog.e("cpu_log","--------------:"+android.os.Build.CPU_ABI);
    }
    @Override
    protected void onResume() {
        super.onResume();
        setOrderTimerAlartUi();
        //删除已下载的文件
        delDownLoadCacheApp();
        //获取用户信息
        getUserAccountInfo();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(myOrderHandler!=null){
            myOrderHandler.removeCallbacksAndMessages(null);
        }
        UpdateAppManager.initUpdate(actContext).destoryTimeTaskUpdateParams();
        destoryAlarmOrderTimer();
        //有米
        YOUMiADUitil.desYOUMIParams(actContext);
        //万普
        AppConnect.getInstance(actContext).close();
    }

    @Override
    public boolean initLocalBroadcastReceiver() {
        return true;
    }

    //========================初始化定时器==================
    private void initAlarmOrderTimer(){
        iCurrenthourOfDay =  ((Integer) SharedPreferencesUtil.getData(actContext,"time_order_hourOfday",-1)).intValue();
        iCurrentminute =  ((Integer)SharedPreferencesUtil.getData(actContext,"time_order_minute",-1)).intValue();
        if(iCurrenthourOfDay!=-1 && iCurrentminute!=-1){
            //开始设置时间
            AlarmManagerUtils.setAlarmParams(appContext, CommonParams.TimerParams.TIMER_ORDER_START_ACTION, CommonParams.TimerParams.TIMER_ORDER_START_REQUEST_CODE, iCurrenthourOfDay, iCurrentminute);
        }
    }

    /**
     * 设置定时任务UI
     */
    private void setOrderTimerAlartUi(){
        iCurrenthourOfDay =  ((Integer) SharedPreferencesUtil.getData(actContext,"time_order_hourOfday",-1)).intValue();
        iCurrentminute =  ((Integer)SharedPreferencesUtil.getData(actContext,"time_order_minute",-1)).intValue();
        if(iCurrenthourOfDay!=-1 && iCurrentminute!=-1){
            //开始设置时间
            tv_order_cache_flag.setText("今日需自动激活(每日 "+iCurrenthourOfDay+":"+iCurrentminute+")");
        }else{
            tv_order_cache_flag.setText("今日需自动激活(未设定时间)");
        }
    }

    /**
     * 销毁任务定时
     */
    private void destoryAlarmOrderTimer(){
        AlarmManagerUtils.cancleAlarmParams(appContext, CommonParams.TimerParams.TIMER_ORDER_START_ACTION, CommonParams.TimerParams.TIMER_ORDER_START_REQUEST_CODE);
    }



    //===============================获取用户信息接口================================
    /**
     * 显示加载进度
     */
    private void showLoadingProgress(){
        if(loading_progress!=null && loading_progress.getVisibility()!= View.VISIBLE){
            loading_progress.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏加载进度
     */
    private void hideLoadingProgress(){
        if(loading_progress!=null && loading_progress.getVisibility()!=View.GONE){
            loading_progress.setVisibility(View.GONE);
        }
    }

    /**
     * 删除已下载的安装包
     */
    private void delDownLoadCacheApp(){
        try {
            File files = Environment.getExternalStoragePublicDirectory(CommonParams.DownLoadFileParams.APP_DOWNLOAD_DIRS);
            KLog.e("----------delDownLoadCacheApp--------------path---"+files.getPath());
            if (files != null && files.exists()) {
                KLog.e("----------delDownLoadCacheApp--------------exists---:"+files.listFiles().length);
                FileUtil.deleteFileDirs(files);
            }

        }catch (Exception e){
            KLog.e("----------delDownLoadCacheApp--------------Exception---:"+e.getMessage());
        }
        //创建文件夹
        try{
            File files = Environment.getExternalStoragePublicDirectory(CommonParams.DownLoadFileParams.APP_DOWNLOAD_DIRS);
            if(files!=null && !files.exists()){
                files.mkdirs();
            }
        }catch (Exception e){

        }

    }
    /**
     * 获取用户信息
     */
    public void getUserAccountInfo(){
        showLoadingProgress();
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("deviceid", DeviceUtils.getImei(appContext));
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("city", MyApplication.strCity);
        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_GET_USER_FIND_ACCOUNT, params, new HttpCallBack<UserAccountModel>() {
            @Override
            public void onSuccess(UserAccountModel data) {
                userAccountModel = data;
                 hideLoadingProgress();
                showUserAccountInfo();
                showUserOrderInfo();
            }

            @Override
            public void onFail(String msg) {
                hideLoadingProgress();
                ToastUtil.showShort(actContext,msg);
            }
        });
    }

    /**
     * 显示用户信息
     */
    private void showUserAccountInfo(){
        if(userAccountModel!=null){
            tv_account.setText(userAccountModel.getUsername()+"资产");
            tv_yiti.setText("已提:"+String.valueOf(userAccountModel.getYitimoney())+"(元)");
            tv_weiti.setText("未提:"+String.valueOf(userAccountModel.getWeitimoney())+"(元)");
            tv_tizhong.setText("提款中:"+String.valueOf(userAccountModel.getTizhongmoney())+"(元)");
            tv_dongjie.setText("任务进行中:"+String.valueOf(userAccountModel.getDongjiemoney())+"(元)");
        }else{
            tv_account.setText("XX资产");
            tv_yiti.setText("已提:0.00(元)");
            tv_weiti.setText("未提:0.00(元)");
            tv_tizhong.setText("提款中:0.00(元)");
            tv_dongjie.setText("任务进行中:0.00(元)");
        }

    }

    /**
     * 获取用户缓存数据
     */
    private void showUserOrderInfo(){
        String strCurrentDate = DateUtil.getCurDateStr("yyyy-MM-dd");
        int iOrderCount= orderDetailsCacheUtils.queryOrderTypeAllCount();
        int iOrderStartCount = orderDetailsCacheUtils.queryOrderTypeStartCount(strCurrentDate);
        int iOrderFinishCount = orderDetailsCacheUtils.queryOrderTypeFinishCount(strCurrentDate);
        tv_order_count.setText("未结算任务总数："+iOrderCount);
        tv_order_renling.setText("今日已认领："+iOrderStartCount);
        tv_order_finish.setText("今日已启动："+iOrderFinishCount);
    }

//=======================升级======================

    /**
     * 开始升级操作
     */
    public void startAppUpdate(){
        //版本检测
        initUpdateDialog("升级检查中...");
        UpdateAppManager.initUpdate(actContext).initTimeTaskUpdateParams();
    }

    //关闭
    public static final int iHanderType_closed_app = 50001;//关闭app
    /**
     * 任务列表handler
     */
    public static class MyOrderHandler extends Handler {
        WeakReference<BaseActivity> softReference;

        public MyOrderHandler(BaseActivity activity) {
            softReference = new WeakReference<BaseActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainNewActivity mActivity = (MainNewActivity) softReference.get();
            if (mActivity != null) {
                int whate = msg.what;
                KLog.e("--------------handleMessage-----------------:" + whate);
                switch (whate) {
                    case iHanderType_closed_app:
                        //关闭程序
                        mActivity.closedApp();
                        break;
                }
            }
        }
    }
    /**
     * 升级操纵
     * @param action
     */
    @Override
    public void getUpdateMyBroadcastReceiver(String action) {
        KLog.e("update_action_log","------action--------------"+action);
        if(!TextUtils.isEmpty(action) && "android.myapp.update.updatestart".equals(action)){
            //开始升级
            showUpdateAlearDialog("联播客升级中...");
        }else if(!TextUtils.isEmpty(action) && "android.myapp.update.updatesuccess".equals(action)){
            //升级成功,关闭程序
            ToastUtil.show(actContext,"升级包已下载，请安装升级包", Toast.LENGTH_SHORT);
            myOrderHandler.sendEmptyMessageDelayed(iHanderType_closed_app,1500);
        }else if(!TextUtils.isEmpty(action) && "android.myapp.update.updatefails".equals(action)){
            //升级失败，
            UpdateAppManager.initUpdate(actContext).destoryTimeTaskUpdateParams();
            dismissUpdateAlearDialog();
            //获取用户信息
            getUserAccountInfo();
        }else if(!TextUtils.isEmpty(action) && "android.myapp.update.updatenormal".equals(action)){
            //不需要升级
            UpdateAppManager.initUpdate(actContext).destoryTimeTaskUpdateParams();
            dismissUpdateAlearDialog();
            //获取用户信息
            getUserAccountInfo();
        }
    }
    //关闭程序
        public void closedApp(){
            finish();
        }
        //====================================网络处理=========================================
        @Override
        public void getMyBroadcastReceiver(String netType) {
            if(NetWorkUtils.isNetworkConnected(actContext) && "WIFI".equals(DeviceUtils.getDeviceAc())){
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.notify_root_title);
                builder.setMessage(R.string.nettype_not_mobile_content);
                builder.setNegativeButton(R.string.setting,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
                                actContext.startActivity(intent);
                            }
                        });
                builder.setCancelable(false);
                builder.show();
            }
        }
    //=================================删除已完成的任务=================================
    private void delOrderTypeCacheInfo(){
        try {
            //卸载
            if (AppUtils.hasApp(actContext, "com.ruimayi.sitemoneyapp")) {
                SystemUtils.uninstallApkSlient("com.ruimayi.sitemoneyapp");
            }
        }catch (Exception e){

        }
        try {
            if (AppUtils.hasApp(actContext, "com.ruiyi.link.ad")) {
                SystemUtils.uninstallApkSlient("com.ruiyi.link.ad");
            }
        }catch (Exception e){

        }
        //清除过期任务
        orderDetailsCacheUtils.clearPastDurOrder(DateUtil.getCurDateStr("yyyy-MM-dd"));
        //卸载过期任务app
        for ( String strappName:MyApplication.appUnInstallPackNameDatas ) {
            try {
                if (AppUtils.hasApp(actContext, strappName)) {
                    SystemUtils.uninstallApkSlient(strappName);
                }
            }catch (Exception e){

            }
        }
    }

    //=============================开始启动自动任务============================


    @Override
    public void getTimerOrderdMyBroadcastReceiver(String action) {
        KLog.e("----------getTimerOrderdMyBroadcastReceiver-----------:"+action);
        if("android.myapp.timer.orders.auto.start".equals(action)){
            //开始执行自动任务
//            //测试数据
//            ArrayList<String> appNameList = new ArrayList<String>();
//            appNameList.add("com.browser2345");
//            MyApplication.iAutoTimerOrderTime =true;
//            Intent timerOrderIntent = new Intent(actContext, TimerOrderService.class);
//            timerOrderIntent.setAction(TimerOrderService.TIMER_ORDER_SERVICE_ACTION_START);
//            timerOrderIntent.putStringArrayListExtra("data",appNameList);
//            actContext.startService(timerOrderIntent);


           List<OrdetTypeTable> orderTypeTableData  = orderDetailsCacheUtils.queryOrderTypeByOrderDurTime(DateUtil.getCurDateStr("yyyy-MM-dd"));
            if(orderTypeTableData!=null && orderTypeTableData.size()>0){
                //有任务需要执行
                ArrayList<String> appNameList = new ArrayList<String>();
                for (OrdetTypeTable beanTable:orderTypeTableData) {
                    if(!TextUtils.isEmpty(beanTable.getAppname()) && AppUtils.hasApp(actContext, beanTable.getAppname())){
                        appNameList.add(beanTable.getAppname());
                    }
                }
                if(appNameList!=null&& !appNameList.isEmpty()){
                    //开启执行服务
                    MyApplication.iAutoTimerOrderTime =true;
                    Intent timerOrderIntent = new Intent(actContext, TimerOrderService.class);
                    timerOrderIntent.setAction(TimerOrderService.TIMER_ORDER_SERVICE_ACTION_START);
                    timerOrderIntent.putStringArrayListExtra("data",appNameList);
                    actContext.startService(timerOrderIntent);
                }else{
                    MyApplication.iAutoTimerOrderTime =false;
                    ToastUtil.showShort(actContext,"目前没有需要自动执行的任务,请尽快认领任务");
                }

            }else{
                MyApplication.iAutoTimerOrderTime =false;
                ToastUtil.showShort(actContext,"目前没有需要自动执行的任务,请尽快认领任务");
            }
        }else if("android.myapp.timer.orders.auto.stop".equals(action)){
            //任务执行完毕
            Intent timerOrderIntent = new Intent(actContext, TimerOrderService.class);
            timerOrderIntent.setAction(TimerOrderService.TIMER_ORDER_SERVICE_ACTION_STOP);
            actContext.startService(timerOrderIntent);
//            //回到主页面

            DeviceUtils.doStartApplicationWithPackageName(actContext,"com.lianboke.link.ad");
//            Intent mainIntent = new Intent(actContext,MainNewActivity.class);
//            //mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//            actContext.startActivity(mainIntent);
        }
    }
}
